package com.x.crm.dao;

import com.x.crm.model.PhoneRecord;
import com.x.framework.dao.BaseDao;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/3/2.
 */

@Repository
public class PhoneRecordDao extends BaseDao{
	private final static String baseQuerySql = "SELECT * FROM CRM_PHONE_RECORD  T1 WHERE T1.PHONE_RECORD_ID > 0 ";
	public List<PhoneRecord> selectPhoneRecordList(PhoneRecord phoneRecord) throws Exception {
		StringBuilder sql = new StringBuilder(baseQuerySql);
		List<Object> params = new ArrayList<>();
		searchCondition(phoneRecord, sql, params);
		sql.append(" ORDER BY T1.CREATED_TIME DESC ");
		return this.queryForList(sql.toString(), PhoneRecord.class, params, phoneRecord);
	}

	private final static String baseQueryConutSql = "SELECT COUNT(PHONE_RECORD_ID) FROM CRM_PHONE_RECORD  T1 WHERE T1.PHONE_RECORD_ID > 0 ";
	public int selectPhoneRecordNum(PhoneRecord phoneRecord) throws Exception {
		StringBuilder sql = new StringBuilder(baseQueryConutSql);
		List<Object> params = new ArrayList<>();
		searchCondition(phoneRecord, sql, params);
		return this.queryForInt(sql.toString(), params);
	}

    public PhoneRecord selectPhoneRecordById(PhoneRecord phoneRecord) throws Exception {
	    StringBuilder sql = new StringBuilder(baseQuerySql);
	    List<Object> params = new ArrayList<Object>();
	    if(this.isNotNull(phoneRecord.getPhoneRecordId())){
	        sql.append("AND T1.PHONE_RECORD_ID = ? ");
	        params.add(phoneRecord.getPhoneRecordId());
	        return this.queryForList(sql.toString(),  PhoneRecord.class, params).get(0);
	    }
	    return new PhoneRecord();
    }

	public void  searchCondition(PhoneRecord phoneRecord, StringBuilder sql, List<Object> params){
		if (this.isNotNull(phoneRecord.getUserId())) {
			sql.append("AND T1.USER_ID = ? ");
			params.add(phoneRecord.getUserId());
		}
		if (this.isNotNull(phoneRecord.getCustomerName())) {
			sql.append("AND T1.CUSTOMER_NAME = ? ");
			params.add(phoneRecord.getCustomerName());
		}
		if (this.isNotNull(phoneRecord.getCustomerPhone())) {
			sql.append("AND T1.CUSTOMER_PHONE = ? ");
			params.add(phoneRecord.getCustomerPhone());
		}
		if (this.isNotNull(phoneRecord.getRecordState())) {
			sql.append("AND T1.RECORD_STATE = ? ");
			params.add(phoneRecord.getRecordState());
		}
	}

}
